﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Booky.Common;
using DataStorage;
using System.Diagnostics;
using System.Configuration;
using AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox;
using AppLimit.CloudComputing.SharpBox;
using Ascend.Windows.Forms;
using BinaryComponents.SuperList;

using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using BinaryComponents.SuperList.Sections;
using BinaryComponents.Utility.Collections;
using Newtonsoft.Json;
using ListControl = BinaryComponents.SuperList.ListControl;


namespace Booky.WinFormsClient
{
    public partial class MainForm : Form
    {
        Repository r = new Repository();

        private bool IsBookmarksLoaded { get; set; }

        AsyncFunc<string, List<Bookmark>> reloadBookmarkListingTask;
        AsyncFunc<string, List<Tag>> reloadTagListingTask;
        AsyncFunc<string, string> onAfterAuthenticateTask;
        AsyncFunc<Bookmark, string> deleteBookmarkTask;
        AsyncFunc<Bookmark, string> updateBookmarkTask;

        public MainForm()
        {
            InitializeComponent();
         
            //InitializeLoginComponents();

            //Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 0, 0));

            reloadBookmarkListingTask = new AsyncFunc<string, List<Bookmark>>(ReloadBookmarkListingTask);
            reloadBookmarkListingTask.Completed += new AsyncFuncCompletedEventHandler<List<Bookmark>>(ReloadBookmarkListingTask_Completed);
            //getAnswer.ProgressChanged += (s, a) => progressBar1.Value = a.ProgressPercentage;

            reloadTagListingTask = new AsyncFunc<string, List<Tag>>(ReloadTagListingTask);
            reloadTagListingTask.Completed += new AsyncFuncCompletedEventHandler<List<Tag>>(ReloadTagListingTask_Completed);

            //onAfterAuthenticateTask = new AsyncFunc<string, string>(OnAfterAuthenticateTask);
            //onAfterAuthenticateTask.Completed += new AsyncFuncCompletedEventHandler<string>(OnAfterAuthenticateTask_Completed);
            //getAnswer.ProgressChanged += (s, a) => progressBar1.Value = a.ProgressPercentage;

            deleteBookmarkTask = new AsyncFunc<Bookmark, string>(DeleteBookmarkTask);
            deleteBookmarkTask.Completed += new AsyncFuncCompletedEventHandler<string>(DeleteBookmarkTask_Completed);
            //getAnswer.ProgressChanged += (s, a) => progressBar1.Value = a.ProgressPercentage;

            updateBookmarkTask = new AsyncFunc<Bookmark, string>(UpdateBookmarkTask);
            updateBookmarkTask.Completed += new AsyncFuncCompletedEventHandler<string>(UpdateBookmarkTask_Completed);
            //getAnswer.ProgressChanged += (s, a) => progressBar1.Value = a.ProgressPercentage;

            this.navigationPane1.NavigationPages.Clear();
            
            this.navigationPane1.SelectedIndexChanged += new EventHandler(navigationPane1_SelectedIndexChanged);
            NavigationPanePage bookmarkNavigationPanePage = new NavigationPanePage();
            bookmarkNavigationPanePage.Name = "dynamicNavigationPane1";
            //Currently it is critical that each NavigationPanePage have a unique name.
            //I think we will add an internal name to remove this requirement in future versions.
            //bookmarkNavigationPanePage.MouseClick += new MouseEventHandler(bookmarkNavigationPanePage_MouseClick); //+= new EventHandler(bookmarkNavigationPanePage_Click);
            bookmarkNavigationPanePage.Text = "Bookmarks";

            Label label1 = new Label();
            label1.Text = "All Bookmarks";
            bookmarkNavigationPanePage.Controls.Add(label1);
            //The label is not required. Just here to show what page is showing.

            this.navigationPane1.NavigationPages.Add(bookmarkNavigationPanePage);

            NavigationPanePage tagNavigationPanePage = new NavigationPanePage();
            tagNavigationPanePage.Name = "dynamicNavigationPane2";
            tagNavigationPanePage.Text = "Tags";

            Label label2 = new Label();
            label2.Text = "All Tags";

            tagNavigationPanePage.Controls.Add(label2);

            this.navigationPane1.NavigationPages.Add(tagNavigationPanePage);

            NavigationPanePage navigationPanePage3 = new NavigationPanePage();
            navigationPanePage3.Name = "dynamicNavigationPane3";
            navigationPanePage3.Text = "Lists";

            Label label3 = new Label();
            label3.Text = "All Lists";

            navigationPanePage3.Controls.Add(label3);

            this.navigationPane1.NavigationPages.Add(navigationPanePage3);

           // pAuthenticated.Visible = false;
            this.BookySplitContainer.Visible = false;
            //listControl1.Visible = false;
            

            this.toolStripMenuItemAddBookmark.Visible = false;
            this.toolStripMenuItemLogout.Visible = false;
            //bool bIsConfigured = IsConfigured();

            //TODO make this async. ...future enhancement
            //if (!CloudRepository.IsAuthenticatedWithSecurityToken())
            //{
            //    pLogin.Visible = true;
            //}
            
            if(!r.IsAuthenticated())
            {
                //Create a new login form and show
                //pLogin.Visible = true;
                AccountSetupForm form = new AccountSetupForm();
                form.FormClosed += new FormClosedEventHandler(form_FormClosed);
                form.ShowDialog();
            }

            //Is the user authenticated to their cloud provider
            if (r.IsAuthenticated()) //CloudRepository.IsAuthenticatedWithSecurityToken() )
            {
                ConfigureBookmarkView();
            }

            //string fileWithPath = args[1];

            //BookmarkJson o = JsonConvert.DeserializeObject<BookmarkJson>("test");
            //MessageBox.Show(o.Url);
        }

        void form_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (r.IsAuthenticated()) 
            {
                ConfigureBookmarkView(true);
            }
        }

        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn
        (
            int nLeftRect, // x-coordinate of upper-left corner
            int nTopRect, // y-coordinate of upper-left corner
            int nRightRect, // x-coordinate of lower-right corner
            int nBottomRect, // y-coordinate of lower-right corner
            int nWidthEllipse, // height of ellipse
            int nHeightEllipse // width of ellipse
        );

        void ReloadBookmarkListingTask_Completed(object sender, AsyncFuncCompletedEventArgs<List<Bookmark>> e)
        {
            if (e.Error != null)
            {
                // Report exception
            }
            else if (e.Cancelled)
            {
                // Ignore
                MessageBox.Show("Operation cancelled");
            }
            else
            {
                //set the gui, etc. 
                this.BookmarkListControl.Items.Clear();
                BookmarkListControl.Items.AddRange(e.Result); 
            }

            //progressBar1.Value = 0;
        }

        void ReloadTagListingTask_Completed(object sender, AsyncFuncCompletedEventArgs<List<Tag>> e)
        {
            if (e.Error != null)
            {
                // Report exception
            }
            else if (e.Cancelled)
            {
                // Ignore
                MessageBox.Show("Operation cancelled");
            }
            else
            {
                //set the gui, etc. 
                this.TagListControl.Items.Clear();
                TagListControl.Items.AddRange(e.Result);
            }

            //progressBar1.Value = 0;
        }

        // Extremely complex stuff
        private List<Bookmark> ReloadBookmarkListingTask(string question, Func<bool> isCancelled, Action<int> reportProgress)
        {
            List<Bookmark> list = r.GetBookmarks();
            return list;
        }

        private List<Tag> ReloadTagListingTask(string question, Func<bool> isCancelled, Action<int> reportProgress)
        {
            List<Tag> list = r.GetTags();
            return list;
        }

        void DeleteBookmarkTask_Completed(object sender, AsyncFuncCompletedEventArgs<string> e)
        {
            if (e.Error != null)
            {
                // Report exception
            }
            else if (e.Cancelled)
            {
                // Ignore
                MessageBox.Show("Operation cancelled");
            }
            else
            {
                //Hide the bookmark detail view after deletion
                
                //set the gui, etc. 
                //this.listControl1.Items.Clear();
                //listControl1.Items.AddRange(e.Result);
                //MessageBox.Show("bookmark deleted");
            }

            //progressBar1.Value = 0;
        }

        void UpdateBookmarkTask_Completed(object sender, AsyncFuncCompletedEventArgs<string> e)
        {
            if (e.Error != null)
            {
                // Report exception
            }
            else if (e.Cancelled)
            {
                // Ignore
                MessageBox.Show("Operation cancelled");
            }
            else
            {
                //Reload the bookmark details panel

                //set the gui, etc. 
                //this.listControl1.Items.Clear();
                //listControl1.Items.AddRange(e.Result);
                //MessageBox.Show("bookmark deleted");
            }

            //progressBar1.Value = 0;
        }

        // Extremely complex stuff
        private string DeleteBookmarkTask(Bookmark b, Func<bool> isCancelled, Action<int> reportProgress)
        {
            r.DeleteBookmarkLocal(b);
            r.DeleteBookmarkCloud(b);
            //List<Bookmark> list = r.GetBookmarks();
            return "asdf";
        }

        private string UpdateBookmarkTask(Bookmark b, Func<bool> isCancelled, Action<int> reportProgress)
        {
            r.UpdateBookmarkLocal(b);
            r.UpdateBookmarkLocalCloud(b);
            //List<Bookmark> list = r.GetBookmarks();
            return "asdf";
        }

        void navigationPane1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (navigationPane1.SelectedIndex)
            {
                case 0:
                    ConfigureBookmarkView();
                    break;
                case 1:
                    ConfigureTagView();
                    break;
                case 2:
                    ConfigureBookmarksListView();
                    break;
                default:
                    ConfigureBookmarkView();
                    break;
            }
        }

        private void ConfigureListsView(bool shouldLoadData = false)
        {
            this.BookmarkSplitContainer.Visible = false;
            MessageBox.Show("in lists");
        }

        private void ConfigureTagView(bool shouldLoadData = false)
        {
            this.BookmarkSplitContainer.Visible = false;
            this.TagSplitContainer.Visible = true;
            TagListControl.Visible = true;
            pTagDetailView.Visible = false;
            if (shouldLoadData)
                LoadTagData();
            //MessageBox.Show("in tag");
        }

        private void LoadTagData()
        {
            reloadTagListingTask.TryInvokeAsync("asdf");
        }

        private void ConfigureBookmarkView(bool shouldLoadData = false)
        {
            //pAuthenticated.Visible = true;
            this.TagSplitContainer.Visible = false;
            this.BookmarkSplitContainer.Visible = true;
            BookmarkListControl.Visible = true;
            
            this.toolStripMenuItemLogout.Visible = true;
            this.toolStripMenuItemAddBookmark.Visible = true;

            ConfigureBookmarksListView();
            //this.BookmarkSplitContainer.Visible = true;
            this.BookySplitContainer.Visible = true;
            pBookmarkDetailView.Visible = false;
            
            if(shouldLoadData)
                LoadBookmarkData();
        }

        private Column tagListingNameColumn;
        private void ConfigureTagsListView()
        {
            if (TagListControl.Columns.Count == 0)
            {
                tagListingNameColumn = new Column("name", "Name", 480, delegate(object item)
                {
                    return ((Bookmark)item).Name;
                });

                TagListControl.MouseClickedRow += new ListControl.RowMouseClickedEventArgsHandler(TagListControl_MouseClickedRow);
                TagListControl.Columns.Add(bookmarkListingNameColumn);
                TagListControl.ShowCustomizeSection = false;
                TagListControl.ShowHeaderSection = false;
            }
        }

        void TagListControl_MouseClickedRow(object sender, ListControl.RowEventArgs eventArgs)
        {
            RowIdentifier ri = TagListControl.SelectedItems[0];

            Tag t = (Tag)ri.Items.FirstOrDefault();

            SelectedTag = t;

            SetTagDetailView();
        }

        private Column bookmarkListingNameColumn;
        private EmailPreviewExample _emailPreviewExample = null;

        private void ConfigureBookmarksListView()
        {
            if (BookmarkListControl.Columns.Count == 0)
            {
                bookmarkListingNameColumn = new Column("name", "Name", 480, delegate(object item)
                {
                    return ((Bookmark)item).Name;
                });

                BookmarkListControl.MouseClickedRow += new ListControl.RowMouseClickedEventArgsHandler(BookmarkListControl_MouseClickedRow);
                BookmarkListControl.Columns.Add(bookmarkListingNameColumn);
                BookmarkListControl.ShowCustomizeSection = false;
                BookmarkListControl.ShowHeaderSection = false;
            }
            //_emailPreviewExample = new EmailPreviewExample(listControl1, EmailPreviewExample.Style.AllRows);

            //wthis.bookmarkListView.Columns.Add("Title",200);
            //wthis.bookmarkListView.Columns.Add("Location",200);
           // this.listView1.ItemActivate += new EventHandler(listView1_ItemActivate);
            //wbookmarkListView.FullRowSelect = false;
        }

        void BookmarkListControl_MouseClickedRow(object sender, ListControl.RowEventArgs eventArgs)
        {
            RowIdentifier ri = BookmarkListControl.SelectedItems[0];
            
            Bookmark b = (Bookmark)ri.Items.FirstOrDefault();

            SelectedBookmark = b;

            SetBookmarkDetailView();
        }

        private void LoadBookmarkData()
        {
            reloadBookmarkListingTask.TryInvokeAsync("asdf");
        }


        private void button1_Click(object sender, EventArgs e)
        {
            AddEditBookmark form = new AddEditBookmark();
            form.FormClosed += new FormClosedEventHandler(AddEditBookmarkForm_Add_FormClosed);
            form.ShowDialog();
        }

        void AddEditBookmarkForm_Add_FormClosed(object sender, FormClosedEventArgs e)
        {
            LoadBookmarkData();
            //On Add Bookmark, insert the bookmark to the top of the listcontrol
            //listControl1.Items.Add();
        }

        void AddEditBookmarkForm_Update_FormClosed(object sender, FormClosedEventArgs e)
        { 
            //Update the selected bookmark
            Bookmark currentBookmark = this.SelectedBookmark;
            //TODO this is synchronous/blocking..we need to async this
            //Refresh the current bookmark from local sql repository
            this.SelectedBookmark = r.GetBookmark(currentBookmark.Id);
            //set this as the selected bookmark

            //Update the bookmark detail view

            SetBookmarkDetailView();

            LoadBookmarkData();
        }

        //private void listView1_Click(object sender, EventArgs e)
        //{
        //    ListViewItem item = ((ListView)sender).SelectedItems[0];
        //    Bookmark bookmark = (Bookmark)item.Tag;
        //    SelectedBookmark = bookmark;

        //    SetBookmarkDetailView();
        //}

        public void InsertBookmarkToListControl(Bookmark b)
        {
            List<Bookmark> list = new List<Bookmark>();
            list.Add(b);

            this.BookmarkListControl.Items.AddRange(list);
        }

        public Bookmark SelectedBookmark { get; set; }

        public Tag SelectedTag { get; set; }

        public Lst SelectedList { get; set; }
 
        private void SetBookmarkDetailView()
        {
            pBookmarkDetailView.Visible = true;
            if (SelectedBookmark != null)
            {
                lblLocation.Text = SelectedBookmark.Url;
                lblName.Text = SelectedBookmark.Name;
                lblDesc.Text = SelectedBookmark.Description;
            }
        }

        private void SetTagDetailView()
        {
            pTagDetailView.Visible = true;
            if (SelectedTag != null)
            {
                lblTagName.Text = SelectedTag.Name;
            }
        }

        //private void SetBookmarkDetailView()
        //{
        //    pBookmarkDetailView.Visible = true;
        //    if (SelectedBookmark != null)
        //    {
        //        lblLocation.Text = SelectedBookmark.Url;
        //        lblName.Text = SelectedBookmark.Name;
        //        lblDesc.Text = SelectedBookmark.Description;
        //    }
        //}

        private void btnOpenBookmark_Click(object sender, EventArgs e)
        {
            if (SelectedBookmark != null)
            {
                try
                {
                    Process.Start(SelectedBookmark.Url);
                }
                catch (SystemException ex)
                {
                    MessageBox.Show("Website could not be loaded");
                }
            }
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //On Logout we drop all tables and delete the security token file
            r.SignoutBooky();
            BookmarkListControl.Items.Clear();
            BookmarkListControl.Visible = false;
            
            this.BookySplitContainer.Visible = false;
            
            //pAuthenticated.Visible = false;
            //pLogin.Visible = true;
            
            this.toolStripMenuItemLogout.Visible = false;
            this.toolStripMenuItemAddBookmark.Visible = false;

            AccountSetupForm form = new AccountSetupForm();
            form.FormClosed += new FormClosedEventHandler(form_FormClosed);
            form.ShowDialog();

            //NavigateToLoginPage();
        }

        private void toolStripMenuItemAddBookmark_Click(object sender, EventArgs e)
        {
            AddEditBookmark form = new AddEditBookmark();
            //form.Parent = this;
            form.Owner = this;
            form.FormClosed += new FormClosedEventHandler(AddEditBookmarkForm_Add_FormClosed);
            form.ShowDialog();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        void btnDeleteBookmark_Click(object sender, System.EventArgs e)
        {
            //splitContainer1ListViewDetailContainer.Panel2
            if (SelectedBookmark != null)
            {
                try
                {
                    BookmarkListControl.Items.Remove(SelectedBookmark);
                    pBookmarkDetailView.Visible = false;
                    //r.DeleteBookmarkLocal(SelectedBookmark);
                    deleteBookmarkTask.TryInvokeAsync(SelectedBookmark);
                    //r.DeleteBookmarkCloud(SelectedBookmark);
                }
                catch (SystemException ex)
                {
                    //MessageBox.Show("Website could not be loaded");
                }
            }
        }

        private void UpdateBookmarkButton_Click(object sender, EventArgs e)
        {
            if (SelectedBookmark != null)
            {
                try
                {
                    AddEditBookmark form = new AddEditBookmark();
                    if (SelectedBookmark != null)
                    {
                        form.ExistingBookmark = SelectedBookmark;
                        form.DataBind();
                    }

                    form.FormClosed += new FormClosedEventHandler(AddEditBookmarkForm_Update_FormClosed); //+= new FormClosedEventHandler(AddEditBookmarkForm_Add_FormClosed);
                    form.ShowDialog();
                    //Update the bookmark in the local sql repository
                    //updateBookmarkTask.TryInvokeAsync(SelectedBookmark);
                    //Remove the item form teh listcontrol
                    
                    //r.UpdateBookmark(SelectedBookmark);
                }
                catch (SystemException ex)
                {
                    //MessageBox.Show("Website could not be loaded");
                }
            }
        }

        private void addTagToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddEditTag form = new AddEditTag();
            //form.Parent = this;
            form.Owner = this;
            form.FormClosed += new FormClosedEventHandler(AddEditTagForm_Add_FormClosed);
            form.ShowDialog();
        }

        void AddEditTagForm_Add_FormClosed(object sender, FormClosedEventArgs e)
        {
            LoadTagData();
            //On Add Bookmark, insert the bookmark to the top of the listcontrol
            //listControl1.Items.Add();
        }
    }
}
//private bool IsConfigured()
//{
//    bool isSetup = false;
//    //Check if this is the first time setup
//        // Get the configuration file.
//    System.Configuration.Configuration config =
//        ConfigurationManager.OpenExeConfiguration(
//        ConfigurationUserLevel.None);

//    // Add an entry to appSettings.
//    int appStgCnt = ConfigurationManager.AppSettings.Count;

//    if (appStgCnt == 3)
//    {
//        isSetup = true;
//    }
//    else
//    {
//        FirstTimeSetup();
//    }

//    return isSetup;
//}

//private void FirstTimeSetup()
//{
//    //Check if this is the first time setup
//    // Get the configuration file.
//    System.Configuration.Configuration config =
//      ConfigurationManager.OpenExeConfiguration(
//      ConfigurationUserLevel.None);

//    string newKey = "IsSetup";

//    bool isSetup = true;

//    config.AppSettings.Settings.Add(newKey, isSetup.ToString());

//    // Save the configuration file.
//    config.Save(ConfigurationSaveMode.Modified);

//    // Force a reload of the changed section.
//    ConfigurationManager.RefreshSection("appSettings");

//}
